<?php

namespace app\api\controller;

use think\facade\Request;
use app\api\service\LoginService;
use app\common\Common;
use app\common\Error;
use app\BaseController;

class Login extends BaseController
{
    private $service;

    public function __construct(LoginService $service)
    {
        $this->service = $service;
    }

    /**
     * 用户登录
     * 
     * @dateTime 2022/09/01
     * @author zhixiang0215@126.com
     * @param string code
     * @return 
     */
    public function login()
    {
        $params = Request::param();

        try {
            validate(\app\api\validate\Login::class)->scene('login')->check($params);
        } catch (\Exception $e) {
            return Common::fail($e->getError());
        }

        // if (!empty($params['link_id'])) {
        //     file_put_contents('./public_login.txt', date('Y-m-d H:i:s').' ：'.$params['link_id'].'；'.json_encode($params).'；'.PHP_EOL, FILE_APPEND);
        // }

        $data = $this->service->userLogin($params, Request::header());

        if (empty($data)) {
            return Common::fail(Error::FAIL_AUTHORIZED_lOGIN);
        }

        return Common::success($data);
    }

    // 添加微信授权获取的用户信息
    public function setWechatUserInfo()
    {
        $params = Request::param();
        $header = Request::header();
        $params['token'] = empty($header['token']) ? '' : $header['token'];

        try {
            validate(\app\api\validate\Login::class)->scene('get_wechat_user_info')->check($params);
        } catch (\Exception $e) {
            return Common::fail($e->getError());
        }

        $result = $this->service->setWechatUserInfo($params);

        return empty($result) ? Common::fail() : Common::success();
    }
}